package com.example.himalaya.view.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.himalaya.R;
import com.example.himalaya.view.adapters.TrackListAdapter;
import com.example.himalaya.base.BaseActivity;
import com.example.himalaya.base.BaseApplication;
import com.example.himalaya.view.callback.IAlbumDetailViewCallback;
import com.example.himalaya.view.callback.IPlayerViewCallback;
import com.example.himalaya.view.callback.ISubscriptionViewCallback;
import com.example.himalaya.presenters.AlbumDetailPresenter;
import com.example.himalaya.presenters.PlayerPresenter;
import com.example.himalaya.presenters.SubscriptionPresenter;
import com.example.himalaya.constants.Constants;
import com.example.himalaya.utils.ImageBlur;
import com.example.himalaya.utils.LogUtil;
import com.example.himalaya.view_component.RoundRectImageView;
import com.example.himalaya.view_component.SobPopWindow;
import com.example.himalaya.view_component.UILoader;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.ximalaya.ting.android.opensdk.model.album.Album;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;

import net.lucode.hackware.magicindicator.buildins.UIUtil;

import java.util.List;

public class DetailActivity extends BaseActivity implements IAlbumDetailViewCallback, UILoader.OnRetryClickListener, TrackListAdapter.ItemClickListener, IPlayerViewCallback, ISubscriptionViewCallback {

    // Constant
    private static final String TAG = "DetailActivity";
    private static final int DEFAULT_PLAY_INDEX = 0;

    // UI object
    private ImageView mLargeCover;              // 显示的大图
    private RoundRectImageView mSmallCover;     // 显示的小图
    private TextView mAlbumTitle;               // 专辑标题
    private TextView mAlbumAuthor;              // 专辑作者

    private RecyclerView mDetailList;
    private FrameLayout mDetailListContainer;
    private UILoader mUiLoader;
    private ImageView mPlayControlBtn;
    private TextView mPlayControlTips;
    private TextView mSubBtn;

    // Other UI Object
    private TwinklingRefreshLayout mRefreshLayout;

    // Adapter
    private TrackListAdapter mTrackListAdapter;

    // List
    private List<Track> mCurrentTracks = null;

    // Logic object
    private PlayerPresenter mPlayerPresenter;
    private AlbumDetailPresenter mAlbumDetailPresenter;
    private SubscriptionPresenter mSubscriptionPresenter;

    // Tool
    private long mMCurrentId = -1;
    private int mCurrentPage;
    private Album mCurrentAlbum = null;
    private String mTrackTitle;


    // flag
    private boolean mIsLoaderMore = false;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

        // 设置上方的导航栏不显示
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        // 设置上方的StatusBar为透明
        getWindow().setStatusBarColor(Color.TRANSPARENT);

        initVariable();
        initListener();
        initPresenter();


        updateSubState();
    }

    private void updateSubState() {
        if (mSubscriptionPresenter != null && mCurrentAlbum != null) {
            boolean isSub = mSubscriptionPresenter.isSub(mCurrentAlbum);

            mSubBtn.setText(isSub ? R.string.cancel_sub_tip_text : R.string.sub_tip_text);
        }
    }

    private void initPresenter() {
        // 这个是专辑详情的presenter
        mAlbumDetailPresenter = AlbumDetailPresenter.getInstance();
        mAlbumDetailPresenter.registerViewCallback(this);

        // 播放器的Presenter
        mPlayerPresenter = PlayerPresenter.getPlayerPresenter();
        mPlayerPresenter.registerViewCallback(this);

        // 订阅相关的Presenter
        mSubscriptionPresenter = SubscriptionPresenter.getInstance();
        mSubscriptionPresenter.registerViewCallback(this);

        mSubscriptionPresenter.getSubscriptionList();
    }


    private void initVariable() {
        // 赋值
        mCurrentPage = Constants.DEFAULT_PAGE;           // The hemalaye require the number must >= 1;

        // 获取对象
        mDetailListContainer = this.findViewById(R.id.detail_list_container);
        mLargeCover = this.findViewById(R.id.iv_large_cover);
        mSmallCover = this.findViewById(R.id.announcer_avatar_detail);
        mAlbumTitle = this.findViewById(R.id.announcer_nickname);

        mAlbumAuthor = this.findViewById(R.id.album_detail_title);

        // 播放控制的图标
        mPlayControlBtn = this.findViewById(R.id.detail_play_control);
        mPlayControlTips = this.findViewById(R.id.play_control_tv);
        mPlayControlTips.setSelected(true);

        mSubBtn = this.findViewById(R.id.detail_sub_btn);

        // 创建对象
        if (mUiLoader == null) {
            mUiLoader = new UILoader(this) {
                @Override
                protected View getSuccessView(ViewGroup container) {
                    return createSuccessView(container);
                }
            };

            mDetailListContainer.removeAllViews();
            mDetailListContainer.addView(mUiLoader);

            mUiLoader.setOnRetryClickListener(DetailActivity.this);
        }


        // 初始化订阅键的状态

    }


    private void initListener() {

        // 订阅按钮事件
        mSubBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mSubscriptionPresenter != null) {
                    Boolean isSub = mSubscriptionPresenter.isSub(mCurrentAlbum);

                    if (isSub) {
                        mSubscriptionPresenter.deleteSubscription(mCurrentAlbum);
                    } else {
                        mSubscriptionPresenter.addSubscription(mCurrentAlbum);
                    }
                }
            }
        });


        // 控制播放的事件
        mPlayControlBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 判断播放器是否有播放列表
                if (mPlayerPresenter != null) {

                    if (!mPlayerPresenter.hasPlayList()) {
                        // 没有就加载
                        handleNoPlayList();
                    }

                    // 有就直接播放
                    handlePlayControl();
                }

            }
        });
    }

    /**
     * 当播放器里面没有播放内容
     * 播放当前界面的节目（Detail)界面
     */
    private void handleNoPlayList() {
        mPlayerPresenter.setPlayList(mCurrentTracks, DEFAULT_PLAY_INDEX);
    }

    private void handlePlayControl() {
        // 控制播放器的状态
        if (mPlayerPresenter.isPlaying()) {
            mPlayerPresenter.pause();
        } else {
            SobPopWindow.getInstance().setListData(mCurrentTracks);
            SobPopWindow.getInstance().setCurrentPlayPosition(DEFAULT_PLAY_INDEX);
            mPlayerPresenter.play();
        }
    }

    private View createSuccessView(ViewGroup container) {
        View detailListView = initSuccessVariable(container);

        initSuccessView();

        initSuccessListener();

        return detailListView;
    }

    private View initSuccessVariable(ViewGroup container) {
        // get element
        View detailListView = LayoutInflater.from(this).inflate(R.layout.item_detail_list, container, false);

        mDetailList = detailListView.findViewById(R.id.album_detail_list);

        mRefreshLayout = detailListView.findViewById(R.id.refresh_layout);
        return detailListView;
    }

    private void initSuccessView() {
        // RecyclerView 使用步骤
        // 1.设置布局管理
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        mDetailList.setLayoutManager(linearLayoutManager);


        // 设置item的上下间距
        mDetailList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.top = UIUtil.dip2px(view.getContext(), 3);
                outRect.bottom = UIUtil.dip2px(view.getContext(), 3);
                outRect.left = UIUtil.dip2px(view.getContext(), 5);
                outRect.right = UIUtil.dip2px(view.getContext(), 5);
            }
        });

        // 2.设置适配器
        mTrackListAdapter = new TrackListAdapter();

        mDetailList.setAdapter(mTrackListAdapter);


//        BezierLayout bezierLayout = new BezierLayout(this);
//        mRefreshLayout.setHeaderView(bezierLayout);
        mRefreshLayout.setMinimumHeight(140);
        mRefreshLayout.setOverScrollBottomShow(false);
    }

    private void initSuccessListener() {
        // 设置监听
        mTrackListAdapter.setItemClickListener(this);  // 每个项的监听


        mRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);

                BaseApplication.getsHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(DetailActivity.this, "刷新成功", Toast.LENGTH_LONG).show();
                        mRefreshLayout.finishRefreshing();
                    }
                }, 2000);
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);

                // 去加载跟多的内容
                if (mAlbumDetailPresenter != null) {
                    mAlbumDetailPresenter.loadMore();
                    mIsLoaderMore = true;
                }

            }
        });      // 刷新的监听
    }

    @Override
    public void onDetailListLoaded(List<Track> tracks) {

        if (mIsLoaderMore && mRefreshLayout != null) {
            mRefreshLayout.finishLoadmore();
            mIsLoaderMore = false;
        }


        this.mCurrentTracks = tracks;

        // 更新/设置UI数据
        // 根据数据结果， 控制UI显示
        if (tracks == null || tracks.size() == 0) {
            mUiLoader.updateStatus(UILoader.UIStatus.EMPTY);
        } else {

            mUiLoader.updateStatus(UILoader.UIStatus.SUCCESS);

            mTrackListAdapter.setData(tracks);
        }
    }


    /**
     * 处理Presenter 发送的错误数据
     */
    @Override
    public void onNetworkError(int errorCode, String errorMsg) {
        mUiLoader.updateStatus(UILoader.UIStatus.ERROR);
    }

    @Override
    public void onAlbumLoaded(Album album) {

        this.mCurrentAlbum = album;

        mMCurrentId = album.getId();

        //  获取专辑的详情内容
        if (mAlbumDetailPresenter != null) {
            mAlbumDetailPresenter.getAlbumDetail((int) album.getId(), mCurrentPage);
        }

        // 进入加载界面
        if (mUiLoader != null) {
            mUiLoader.updateStatus(UILoader.UIStatus.LOADING);
        }

        if (mAlbumTitle != null) {
            mAlbumTitle.setText(album.getAlbumTitle());
        }

        if (mAlbumAuthor != null) {
            mAlbumAuthor.setText(album.getAnnouncer().getNickname());
        }

        String coverUrlLarge = album.getCoverUrlLarge();

        if (TextUtils.isEmpty(coverUrlLarge)) {


            mLargeCover.setImageResource(R.mipmap.default_picture);

        } else {
            if (mLargeCover != null) {

                Picasso.with(this).load(album.getCoverUrlLarge()).into(mLargeCover, new Callback() {
                    @Override
                    public void onSuccess() {
                        Drawable drawable = mLargeCover.getDrawable();

                        if (drawable != null) {
                            // 做一个毛玻璃的效果
                            ImageBlur.makeBlur(mLargeCover, DetailActivity.this);
                        }
                    }

                    @Override
                    public void onError() {
                        mLargeCover.setImageResource(R.mipmap.default_picture);


                        LogUtil.d(TAG, "制作详情界面的毛玻璃出错了");
                    }
                });
            }
        }

        if (mSmallCover != null && !TextUtils.isEmpty(album.getCoverUrlLarge())) {
            Picasso.with(this).load(album.getCoverUrlLarge()).into(mSmallCover);
        } else {
            assert mSmallCover != null;
            mSmallCover.setImageResource(R.mipmap.default_picture);
        }
    }


    @Override
    public void onLoaderMoreFinished(int size) {
        if (size > 0) {
            Toast.makeText(this, "成功加载" + size + "条节目", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "没有跟多节目了", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onRefreshFinished(int size) {

    }

    @Override
    public void onRetryClick() {
        // 这里表示用户网络不佳时，点击从新加载
        //  获取专辑的详情内容
        if (mAlbumDetailPresenter != null) {
            mAlbumDetailPresenter.getAlbumDetail((int) mMCurrentId, mCurrentPage);
        }
    }

    @Override
    public void onItemClick(List<Track> detailData, int position) {
        // 设置播放器的数据
        PlayerPresenter playerPresenter = PlayerPresenter.getPlayerPresenter();

        playerPresenter.setPlayList(detailData, position);

        // 跳转到播放器界面
        Intent intent = new Intent(this, PlayerViewActivity.class);

        startActivity(intent);
    }

    @Override
    public void onPlayStart() {
        // 修改图标为暂停， 文字修改为正在播放

        if (mPlayControlBtn != null) {
            mPlayControlBtn.setImageResource(R.drawable.selector_play_control_pause);
            mPlayControlTips.setText(mTrackTitle);
        }
    }

    @Override
    public void onPlayPause() {
        // 修改图标为暂停， 文字修改为正在播放
        if (mPlayControlBtn != null) {
            mPlayControlBtn.setImageResource(R.drawable.selector_play_control_play);
            mPlayControlTips.setText(mTrackTitle);
        }
    }

    @Override
    public void onPlayStop() {
        // 修改图标为暂停， 文字修改为正在播放
        if (mPlayControlBtn != null) {
            mPlayControlBtn.setImageResource(R.drawable.selector_play_control_play);
            mPlayControlTips.setText(R.string.click_play_tips_text);
        }
    }

    @Override
    public void onPlayError() {

    }

    @Override
    public void nextPlay(Track track) {

    }

    @Override
    public void onPrePlay(Track track) {

    }

    @Override
    public void onListLoaded(List<Track> list) {

    }

    @Override
    public void onPlayModeChange(XmPlayListControl.PlayMode playMode) {

    }

    @Override
    public void onAdLoading() {

    }

    @Override
    public void onAdFinished() {

    }

    @Override
    public void onProgressChange(int currPos, int total) {

    }

    @Override
    public void onTrackUpdate(Track track, int playIndex) {
        if (track != null) {
            mTrackTitle = track.getTrackTitle();

            if (!TextUtils.isEmpty(mTrackTitle) && mPlayControlTips != null) {
                mPlayControlTips.setText(mTrackTitle);
            }
        }
    }

    @Override
    public void updateListOrder(boolean isReverse) {

    }

    @Override
    public void onAddResult(boolean isSuccess) {

        if (isSuccess) {
            mSubBtn.setText(R.string.cancel_sub_tip_text);
        }

        Toast.makeText(DetailActivity.this, "添加订阅" + (isSuccess ? "成功" : "失败"), Toast.LENGTH_LONG).show();
    }

    @Override
    public void onDeleteResult(boolean isSuccess) {
        if (isSuccess) {
            mSubBtn.setText(R.string.sub_tip_text);
        }

        Toast.makeText(DetailActivity.this, "删除订阅" + (isSuccess ? "成功" : "失败"), Toast.LENGTH_LONG).show();
    }

    @Override
    public void onSubscriptsLoaded(List<Album> albums) {

    }

    @Override
    public void onSubFull() {
        Toast.makeText(this, "订阅失败，订阅太多了 > " + Constants.MAX_SUB_COUNT, Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mAlbumDetailPresenter != null) {
            mAlbumDetailPresenter.unRegisterViewCallback(this);
        }

        if (mSubscriptionPresenter != null) {
            mSubscriptionPresenter.unRegisterViewCallback(this);

        }

        if (mPlayerPresenter != null) {
            mPlayerPresenter.unRegisterViewCallback(this);
        }
    }
}
